package com.markby.fscm.cryptogram.domain.standard0009;

import com.markby.fscm.cryptogram.uitls.HexUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.bouncycastle.asn1.ASN1BitString;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERBitString;

import java.io.IOException;
import java.math.BigInteger;
import java.security.interfaces.ECPublicKey;

/**
 * 0009规范 SM2公钥格式
 * 04||x||y
 * SM2PublicKey ::= BIT STRING
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class SM2PublicKey extends ASN1Object {

    ASN1BitString publicKey;
    byte[] pubKey;

    public SM2PublicKey(ECPublicKey publicKey) throws IOException {
        // 04||x||y

        BigInteger affineX = publicKey.getW().getAffineX();
        BigInteger affineY = publicKey.getW().getAffineY();


        byte[] pubKey = new byte[65];
        pubKey[0] = 0x04;

        byte[] xBytesTmp = affineX.toByteArray();
        System.arraycopy(xBytesTmp, xBytesTmp.length - 32, pubKey, 1, 32);
        System.out.println("xBytes.length:" + xBytesTmp.length);
        System.out.println("xBytes:" + HexUtils.hexify_haveSpace(xBytesTmp));

        byte[] yBytesTmp = affineY.toByteArray();
        System.arraycopy(yBytesTmp, yBytesTmp.length - 32, pubKey, 33, 32);
        System.out.println("yBytesTmp.length:" + yBytesTmp.length);
        System.out.println("yBytesTmp:" + HexUtils.hexify_haveSpace(yBytesTmp));

        this.publicKey = new DERBitString(pubKey);
        this.pubKey = pubKey;
    }

    public SM2PublicKey(ASN1BitString publicKey) {
        this.publicKey = publicKey;
    }

    public static SM2PublicKey getInstance(Object obj) {
        if (obj instanceof SM2PublicKey) {
            return (SM2PublicKey) obj;
        } else if (obj != null) {
            return new SM2PublicKey(ASN1BitString.getInstance(obj));

        }
        return null;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        return publicKey;
    }
}
